<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('编辑')"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body>
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="form-user-add" class="form-horizontal">
                <div class="select-list">
                    <input id="childId" name="childId" type="hidden" th:value="*{childId}"/>
                    <input id="projectType" name="projectType" type="hidden" th:value="*{projectType}"/>
                    <input id="scheduleTime" name="scheduleTime" type="hidden" th:value="*{scheduleTime}"/>
                    <ul>
                        <li>
                            <label style="width: 80px">学生姓名：</label>
                            <input type="text" name="childName" readonly="true" th:value="*{childName}"/>
                        </li>
                        <li>
                            <label style="width: 80px">年龄：</label>
                            <input type="text" name="childAge" readonly="true" th:value="*{childAge}"/>
                        </li>
                        <li>
                            <label style="width: 80px">月份：</label>
                            <input type="text" name="monthTime" readonly="true" th:value="*{monthTime}"/>
                        </li>
                        <a style="margin-left: 20px" class="btn btn-primary btn-rounded btn-sm" onclick="manageProgram()">增加巩固项目</a>
                    </ul>
                </div>
            </form>
            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
            <label style="size: 20px;color: #1a2226; font-weight: bolder;margin-top: 30px">巩固项目</label>
            <div id="consolidates">
                <div>暂无数据</div>
            </div>
            <div class="col-sm-offset-5 col-sm-10">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭</button>
            </div>
        </div>

    </div>

</div>


<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-js"/>
<th:block th:include="include :: datetimepicker-js" />
<script th:inline="javascript">
    var consolidateData = [];
    var prefix = ctx + "education/childtrainingProgram";
    var editPrefix = ctx + "education/schedule";
    $(function () {
        var childId = $("#childId").val();
        var projectType = $("#projectType").val();
        var scheduleTime = $("#scheduleTime").val();
        var data ={
            childId:childId,
            projectType:projectType,
            scheduleTime:scheduleTime
        }
        $.ajax({
            url: editPrefix+"/listConsolidates",
            type: "post",
            contentType:"application/json",
            data:JSON.stringify(data),
            success: function(result) {
                if (result.code == 0) {
                   renderTable(result.data);
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        })
    });

    $(function () {
        var options = {
            url: prefix + '/findByChildAndProjecttypeTable',
            rememberSelected: true,
            pagination: false,
            showSearch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            queryParams: queryParams,
            rowStyle:rowStyle,
            columns: [
                {
                    field: 'state',
                    checkbox: true,
                    formatter:function(value,row,index){
                        if (row.isChoosed == 1)
                            return {
                                checked : true
                            };
                        return value;
                    }
                },

                {
                    field: 'id',
                    title: '',
                    visible: false

                },
                {
                    field: 'trainingNum',
                    align: "center",
                    visible: false
                },
                {
                    title: '题号',
                    formatter: function (value, row, index) {
                        var data= $('#bootstrap-table').bootstrapTable('getData',true);
                        if(index == 0){
                            data[index].curIndex = 1;
                            return 1;
                        }
                        else {
                            var pre = data[index-1];
                            var cur = data[index];
                            if(pre.trainingPlan == '1'){
                              if(cur.trainingPlan == '1'){
                                  return pre.curIndex +1;
                                  data[index].curIndex = (pre.curIndex +1);
                              }
                              else {
                                  data[index].curIndex = pre.curIndex;
                                  return pre.curIndex;
                              }

                            }
                            else {
                                data[index].curIndex = pre.curIndex+1;
                                return pre.curIndex+1;
                            }

                        }

                    }
                },
                {
                    field: 'trainingPlan',
                    title: '类型',
                    align: "center",
                    formatter: function (value, row, index) {
                        var actions = [];
                        if ($.common.isNotEmpty(value)) {
                            if(value == '1'){
                                actions.push($.common.sprintf("<span class='%s'>%s</span>", "default","A"));
                            }
                            else {
                                actions.push($.common.sprintf("<span class='%s'>%s</span>", "default","B"));
                            }
                        }
                        return actions.join('');
                    }
                },
                {
                    field: 'trainingContent',
                    title: '项目描述',
                    align: "center"
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="editTrainingProgram(\'' + row.id+'\')"><i class="fa fa-edit"></i>编辑</a> ');
                        if(row.afterReplaceId!=null && row.afterReplaceId!=''){
                           actions.push('&nbsp; <a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="revokeTrainingProgram(\'' + row.id+'\')"><i class="fa fa-reply"></i>撤销</a>');
                        }
                        if(row.afterReplaceId==null || row.afterReplaceId==''){
                            actions.push('&nbsp;  <a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="replaceTrainingProgram(\'' + row.id+'\')"><i class="fa fa-retweet"></i>替换项目</a>');
                        }
                        return actions.join('');
                    }
                }
                ]
        };
        $.table.init(options);
        var formData = new FormData();
        var childId = $("#childId").val();
        var projectType = $("#projectType").val();
        var scheduleTime = $("#scheduleTime").val();
        formData.set("childId", childId);
        formData.set("pageSize", 10000);
        formData.set("projectType", projectType);
        formData.set("trainingProgramNumber", scheduleTime);
        formData.set("trainingType", 2);
        $.ajax({
            url: prefix+"/findByChildAndProjecttypeTable",
            cache: false,
            contentType: false,
            processData: false,
            type: "post",
            data:formData,
            success: function(result) {
                if (result.code == 0) {
                   renderTable(result.rows);
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        })
    });

    /* 老师修改标准 */
    function editTrainingProgram(id) {
        var url = editPrefix + "/editTraining/" + id;
        $.modal.open("编辑", url, '800', '300');
    }
    /* 老师替换 */
    function replaceTrainingProgram(id) {
        $.modal.openFull("替换项目", editPrefix+"/replaceTrainingProgram/"+id);
    }

    /* 老师替换 */
    function revokeTrainingProgram(id) {
        $.ajax({
            cache: true,
            type: "POST",
            url: editPrefix + "/saveRevokeProgram",
            data: {"id":id},
            error: function (request) {
                $.modal.alertError("系统错误");
            },
            success: function (data) {
                if (data.code == 0) {
                    // $.modal.close();
                    // parent.submitSelect();
                    $.table.search();
                } else {
                    $.modal.alertError(data.msg);
                }
            }
        });
    }


    function queryParams(params) {
        var childId = $("#childId").val();
        var projectType = $("#projectType").val();
        var scheduleTime = $("#scheduleTime").val();
        var search = $.table.queryParams(params);
        search.childId = childId;
        search.pageSize = 10000;
        search.projectType = projectType;
        search.trainingProgramNumber = scheduleTime;
        search.trainingType = 1;
        return search;
    }


    function rowStyle(row, index) {
        var data= $('#bootstrap-table').bootstrapTable('getData',true);
        if(index == 0){
            data[index].corlorIndex=1;
            return {css:{'background-color':'#FFFFFF'}};
        }
        else {
            if(data[index].trainingNum == data[index-1].trainingNum){
                data[index].corlorIndex =data[index-1].corlorIndex;
                if(data[index-1].corlorIndex==1){
                    return {css:{'background-color':'#FFFFFF'}};
                }
                else {
                    return {css:{'background-color':'#F2F2F2'}};
                }

            }
            else {
                if(data[index-1].corlorIndex==1) {
                    data[index].corlorIndex = 3;
                    return {css:{'background-color':'#F2F2F2'}};
                }
                else {
                    data[index].corlorIndex = 1;
                    return {css:{'background-color':'#FFFFFF'}};
                }
            }
        }
        return {};
    }

    function refresh(){
        $.table.search();
    }

    function manageProgram() {
        var childId = $("#childId").val();
        var projectType = $("#projectType").val();
        var scheduleTime = $("#scheduleTime").val();
        $.modal.openFull("巩固项目", editPrefix+"/addConsolidate/"+childId+"/"+projectType+"/"+scheduleTime);
    }

    function renderTable(data){
        consolidateData = data;
        $('#consolidates').html("");
        var htmlStr = ""
        if(!data || data.length == 0){
            htmlStr = "<div>暂无数据</div>";
        }
        else {
            for(var i=0;i<data.length;i++){
                htmlStr= htmlStr+"<div style='margin-top: 20px'>" +
                "<a class='btn btn-success btn-xs' href='javascript:void(0)' onclick=\"delConsolidate(" + i+")\">删除</a>"+
                "<label style='margin-left: 30px'>"+(i+1)+ ".&nbsp;&nbsp;"+data[i].trainingContent+"</label>"
                "</div>"
            }
        }
        $('#consolidates').html(htmlStr);
    };

    function delConsolidate(i) {
        consolidateData.splice(i,1);
        renderTable(consolidateData);
    }

    function submitSelect() {
        var rows = $('#bootstrap-table').bootstrapTable('getAllSelections');
        if(rows && rows.length >0){
            submitHandler(1);
        }
        else {
            refresh();
        }

    }


    function submitHandler(check) {
        var rows = $.table.selectFirstColumns();
        // if (rows.length == 0) {
        //     $.modal.alertWarning("请至少选择一条记录");
        //     return;
        // }
        if(consolidateData.length>3){
            $.modal.alertWarning("最多只能选择3个待巩固项目");
            return;
        }
        var data= $('#bootstrap-table').bootstrapTable('getData',true);
        var childId = $("#childId").val();
        var projectType = $("#projectType").val();
        var scheduleTime = $("#scheduleTime").val();
        //按顺序排列
        var arrays = [];
        var rows = $('#bootstrap-table').bootstrapTable('getAllSelections');
        if(rows){
            for(var i=0;i<rows.length;i++){
                arrays.push(rows[i].id)
            }
        }
        var programeIds = [];
        var programeAs = [];
        //在列表的序号
        var curIndexs = [];
        var relateTrainingProgramIds = [];
        if(data && arrays){
            for(var i=0;i<data.length;i++){
                for(var j=0;j<arrays.length;j++){
                    if(data[i].id == arrays[j]){
                        programeIds.push(data[i].id);
                        curIndexs.push(data[i].curIndex)
                        relateTrainingProgramIds.push(data[i].trainingProgramId)
                    }
                }

                //表格里面planA的项目数
                if(data[i].trainingPlan && data[i].trainingPlan == '1'){
                    programeAs.push(data[i].id);
                }
            }
            //选择的数量必须和planA的相同
            if(programeAs.length != arrays.length){
                $.modal.alertError("请选择正确数量的项目数");
                return;
            }
        }
        if(relateTrainingProgramIds && consolidateData){
            for(var i=0;i<relateTrainingProgramIds.length;i++){
                for(var j=0;j<consolidateData.length;j++){
                    if(relateTrainingProgramIds[i] == consolidateData[j].trainingProgramId){
                        $.modal.alertError("选中的第"+(i+1)+"行与第"+(j+1)+"个巩固项目相同");
                        return;
                    }
                }}
        }

        var data ={
            programeIds: programeIds,
            consolidates:consolidateData,
            childId:childId,
            projectType:projectType,
            curIndexs:curIndexs,
            scheduleTime:scheduleTime,
            selectCenterId:localStorage.getItem('selectCenterId')
        }
        $.ajax({
            url: editPrefix+"/save",
            type: "post",
            contentType:"application/json",
            data:JSON.stringify(data),
            success: function(result) {
                if (result.code == 0) {
                    if(check){
                        refresh();
                        $.modal.alertSuccess("保存成功");
                    }
                    else {
                        $.modal.alertSuccess("保存成功");
                        setTimeout(function () {
                            closeItem();
                        }, 1000);
                    }
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        })
    }
</script>
</body>
</html>